/**
 * indexedDB数据库封装
 * @param {*} db_name 数据库名称
 * @param {*} table_name 表名称
 * @param {*} version 数据库版本
 */
var inquiryDB = function (db_name, table_name, version = 1) {
    if (!db_name) {
        alert('初始化数据库参数错误');
        return false;
    }

    // 检测是否支持indexDB
    var indexedDB =
        window.indexedDB ||
        window.webkitIndexedDB ||
        window.mozIndexedDB ||
        window.msIndexedDB;
    if (!indexedDB) {
        alert('你的浏览器不支持IndexedDB');
        return false;
    }

    var obj = new Object();
    obj.name = db_name;
    obj.version = version;
    obj.db = {};
    // 初始化表名
    obj.tableName = table_name;

    /**
     * 新增一条聊天记录
     * @param {*} msg 消息内容
     * @param {*} cb 回调
     */
    obj.addMsg = function (msg, cb) {
        obj.db.onsuccess = function (evt) {
            var db = evt.target.result;
            //使用事务
            var store = db.transaction(obj.tableName, "readwrite").objectStore(obj.tableName);
            var save = store.add(msg);
            cb(save);
        }
    }

    /**
     * 查询全部聊天记录
     * @param {*} cb 回调函数
     */
    obj.getDataAll = function (cb) {
        //查询到结果
        obj.db.onsuccess = function (e) {
            var db = e.target.result;
            var store = db.transaction(obj.tableName, 'readwrite').objectStore(obj.tableName);
            var rowData = [];
            store.openCursor().onsuccess = function (event) {
                var cursor = event.target.result;
                if (!cursor && cb) {
                    cb({
                        data: rowData
                    });
                    return;
                }
                rowData.push(cursor.value);
                cursor.continue();
            };
        };
    }

    /**
     * 根据键查询聊天记录
     * @param {*} key 查找键值
     * @param {*} cb 回调函数
     */
    obj.getDataKey = function (key, cb) {
        //查询到结果
        obj.db.onsuccess = function (e) {
            var db = e.target.result;
            var store = db.transaction(obj.tableName, 'readwrite').objectStore(obj.tableName);
            var res = store.get(key);
            res.onsuccess = function (event) {
                var data = event.target.result;
                cb({
                    data: data
                });
            };
        };
    }

    /**
     * 根据索引查询聊天记录
     * @param {*} indexKey 查找索引
     * @param {*} value 查找值
     * @param {*} cb 回调函数
     */
    obj.getDataIndexKey = function (indexKey, value, cb) {
        //查询到结果
        obj.db.onsuccess = function (e) {
            var db = e.target.result;
            var store = db.transaction(obj.tableName, 'readwrite').objectStore(obj.tableName);
            var res = store.index(indexKey);
            res.get(value).onsuccess = function (event) {
                var data = event.target.result;
                cb({
                    data: data
                });
            };
        };
    }

    /**
     * 分页显示数据
     * @param {*} page 页数
     * @param {*} limit 条数
     * @param {*} cb 回调
     */
    obj.getDataByPager = function (page, limit = 15, cb) {
        //查询到结果
        obj.db.onsuccess = function (e) {
            var db = e.target.result;
            var store = db.transaction(obj.tableName, 'readwrite').objectStore(obj.tableName);
            // 数据总数
            var count = store.count();
            count.onsuccess = function (c_e) {
                var totalNum =  c_e.target.result;
                // 第一页
                store.openCursor().onsuccess = function (k_e) {
                    var cursor =  k_e.target.result;
                    // 正负容错
                    limit = totalNum < limit ? totalNum : limit;
                    if (!cursor) {
                        cb({
                            data: [],
                            total_page: 0,
                            r_page: 0,
                        });
                        return;
                    }
                    // 第一个键值
                    var key = cursor.key;
                    // 结束点
                    var end = key + (totalNum - 1) - ((page -1) * limit);
                    // 起始点
                    var start = end - (limit - 1) - ((page -1) * limit);
                    // console.log(c_e);
                    // console.log(start, end, page, limit, key, totalNum);
                    // 分页处理, 获取数据
                    var boundKeyRange = IDBKeyRange.bound(start, end, false, false);
                    var rowData = [];
                    store.openCursor(boundKeyRange).onsuccess = function (event) {
                        var cursor = event.target.result;
                        if (!cursor && cb) {
                            cb({
                                data: rowData,
                                total_page: Math.ceil(totalNum / limit),
                                r_page: page,
                            });
                            return;
                        }
                        rowData.push(cursor.value);
                        cursor.continue();
                    };
                }
            }
        };
    }

    /**
     * 删除聊天记录
     * @param {*} cb 回调函数
     */
    obj.delDataAll = function (cb) {
        //查询到结果
        obj.db.onsuccess = function (e) {
            var db = e.target.result;
            var store = db.transaction(obj.tableName, 'readwrite').objectStore(obj.tableName);
            console.log(store);
            var result = store.clear();
            cb(result);
        };
    }

    /**
     * 创建表
     */
    obj.addTable = function (result) {
        if (!result.objectStoreNames.contains(obj.tableName)) {
            return result.createObjectStore(obj.tableName, {
                autoIncrement: true,
                keyPath:"id",
            });
        }
    }

    /**
     * 删除表
     */
    obj.delTable = function () {
        window.indexedDB.deleteDatabase(obj.table_name);
    }

    /**
     * 创建数据库
     */
    obj.initDB = function () {
        var version = obj.version || 1;
        obj.db = window.indexedDB.open(obj.name, version);
        obj.db.onerror = function (e) {
            console.log(e.currentTarget.error.message);
        };
        obj.db.onsuccess = function (e) {
            // obj.db = e.target.result;
            console.log('数据库连接成功');
        };
        obj.db.onupgradeneeded = function (e) {
            console.log(`数据库版本: ${version}`);
            var store = obj.addTable(e.target.result);
            store.createIndex('msg_id','msg_id',{unique:false}); 
        };
    }

    // 初始化数据库, indexedDB是异步的所以进行延迟返回
    obj.initDB();
    return obj;   
};